package com.java.computeronline.model.blo;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.java.computeronline.model.entity.Product;

public class ProductBLO {

	@SuppressWarnings("unchecked")
	public List<Product> list() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Product> products = null;
		Query query = pm.newQuery(Product.class, "deleted == value");
		query.declareParameters("Integer value");
		products = (List<Product>)query.execute(0);
        return products;
	}
	
	@SuppressWarnings("unchecked")
	public List<Product> inventoryProduct(){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<Product> products = null;
		Query query = pm.newQuery(Product.class,
                "deleted == 0" +
                " && quantity > 0");
		products = (List<Product>)query.execute();
        return products;
	}
	
	public Product getById(Long id){
		Product product = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			product = pm.getObjectById(Product.class, id);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			pm.close();
		}
		return product;
	}
	
	public Product add(Product product) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
            pm.makePersistent(product);
        }catch(Exception ex){
        	ex.printStackTrace();
        } finally {
            pm.close();
        }
		return product;
	}
	
	public Product delete(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Product product;
		try {
			pm.currentTransaction().begin();
			product = pm.getObjectById(Product.class, id);
            pm.deletePersistent(product);
            pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return product;
	}
	
	public Product edit(Product prod){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Product product;
		try {
			pm.currentTransaction().begin();
			product = pm.getObjectById(Product.class, prod.getId());
			product.setCategory(prod.getCategory());
			product.setDescription(prod.getDescription());
			product.setImage(prod.getImage());
			product.setLastModified(new Date());
			product.setManufacturer(prod.getManufacturer());
			product.setName(prod.getName());
			product.setPrice(prod.getPrice());
			product.setStatus(prod.getStatus());
			product.setUnit(prod.getUnit());
            pm.makePersistent(product);
			pm.currentTransaction().commit();
        }catch(Exception ex){
        	pm.currentTransaction().rollback();
			throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
		return product;
	}
}
